<!-- 地址定位 -->
<template>
    <view class="position-page">
        <!-- 状态栏占位 -->
        <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

        <!-- 自定义导航栏 -->
        <view class="custom-nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
            <view class="nav-back" @click="goBack">
                <uni-icons type="left" size="20" color="#333333"></uni-icons>
            </view>
            <view class="nav-title">地址定位</view>
        </view>

        <!-- 搜索框 -->
        <view class="search-bar">
            <input class="search-input" v-model="keyword" placeholder="快速搜索你的位置" confirm-type="search"
                @confirm="handleSearch" />
        </view>

        <!-- 地图 -->
        <map id="map" class="map" :latitude="latitude" :longitude="longitude" :markers="markers" :scale="16"
            :show-location="true" @regionchange="onMapRegionChange"></map>

        <!-- 结果列表 -->
        <scroll-view class="result-list" scroll-y>
            <view v-for="(item, index) in resultList" :key="index" class="result-item" @click="selectLocation(item)">
                <view class="item-left">
                    <view class="poi-title" :class="{ active: index === 0 }">{{ item.title }}</view>
                    <view class="poi-address">{{ item.address }}</view>
                </view>
                <view class="item-right" v-if="typeof item._distance === 'number'">
                    <text class="distance">距离：{{ formatDistance(item._distance) }}</text>
                </view>
            </view>
            <view v-if="!loading && resultList.length === 0" class="no-data">暂无结果</view>
        </scroll-view>
    </view>
</template>

<script>
import { tencent_map } from '@/static/public.js';

export default {
    data() {
        return {
            statusBarHeight: 0,
            keyword: '',
            latitude: 39.909, // 默认北京天安门
            longitude: 116.397,
            markers: [],
            resultList: [],
            loading: false,
            tencent_map: tencent_map
        };
    },
    onLoad() {
        this.getStatusBarHeight();
        this.ensureLocationPermission();
    },
    methods: {
        // 状态栏
        getStatusBarHeight() {
            try {
                const systemInfo = uni.getSystemInfoSync();
                this.statusBarHeight = systemInfo.statusBarHeight || 0;
            } catch (e) {
                this.statusBarHeight = 20;
            }
        },
        // 返回
        goBack() {
            uni.navigateBack();
        },
        // 申请定位权限并初始化
        ensureLocationPermission() {
            // #ifdef MP-WEIXIN
            uni.getSetting({
                success: (res) => {
                    const hasAuth = res.authSetting && res.authSetting['scope.userLocation'];
                    if (hasAuth) {
                        this.initLocation();
                    } else {
                        uni.authorize({
                            scope: 'scope.userLocation',
                            success: () => {
                                this.initLocation();
                            },
                            fail: () => {
                                uni.showModal({
                                    title: '需要定位权限',
                                    content: '用于获取当前位置，是否前往设置开启？',
                                    success: (m) => {
                                        if (m.confirm) {
                                            uni.openSetting({
                                                success: (s) => {
                                                    if (s.authSetting && s.authSetting['scope.userLocation']) {
                                                        this.initLocation();
                                                    }
                                                }
                                            });
                                        } else {
                                            // 用户拒绝，仍然展示默认位置的周边
                                            this.initLocation(/* fallback */);
                                        }
                                    }
                                });
                            }
                        });
                    }
                },
                fail: () => {
                    this.initLocation();
                }
            });
            // #endif

            // #ifndef MP-WEIXIN
            this.initLocation();
            // #endif
        },

        // 初始化定位
        initLocation() {
            uni.getLocation({
                type: 'gcj02',
                success: (res) => {
                    this.latitude = res.latitude;
                    this.longitude = res.longitude;
                    this.updateMarker(res.latitude, res.longitude, '当前位置');
                    // 初始拉取周边
                    this.searchNearby();
                },
                fail: () => {
                    // 即使失败也尝试搜索默认点
                    this.updateMarker(this.latitude, this.longitude, '当前位置');
                    this.searchNearby();
                }
            });
        },
        // 地图范围变化（拖动后刷新周边）
        onMapRegionChange(e) {
            if (e.type === 'end') {
                // 获取中心点坐标
                const ctx = uni.createMapContext('map', this);
                // 小程序里 createMapContext 不能直接拿中心点，这里保持当前中心
                // 简化处理：拖动后不自动刷新，保留按钮/搜索触发
            }
        },
        // 搜索确认
        handleSearch() {
            if (!this.keyword || this.keyword.trim() === '') {
                this.searchNearby();
                return;
            }
            this.searchByKeyword(this.keyword.trim());
        },
        // 周边搜索
        async searchNearby() {
            this.loading = true;
            try {
                const res = await uni.request({
                    url: `${tencent_map.api}/ws/place/v1/search`,
                    method: 'GET',
                    data: {
                        key: tencent_map.key,
                        keyword: '小区,饭店,超市,学校,公寓',
                        boundary: `nearby(${this.latitude},${this.longitude},3000)`, // 3km
                        page_size: 20,
                        page_index: 1
                    }
                });
                if (res.statusCode !== 200) {
                    throw new Error('request fail, statusCode: ' + res.statusCode);
                }
                const list = (res.data && res.data.data) ? res.data.data : [];
                this.resultList = list.map((p) => ({
                    title: p.title,
                    address: p.address || '',
                    location: p.location || p._location || { lat: p.latitude, lng: p.longitude },
                    _distance: p._distance
                }));
            } catch (err) {
                console.error('周边搜索失败:', err);
                this.resultList = [];
            } finally {
                this.loading = false;
            }
        },
        // 关键字搜索
        async searchByKeyword(keyword) {
            this.loading = true;
            try {
                const res = await uni.request({
                    url: `${tencent_map.api}/ws/place/v1/search`,
                    method: 'GET',
                    data: {
                        key: tencent_map.key,
                        keyword,
                        boundary: `nearby(${this.latitude},${this.longitude},10000)`, // 10km
                        page_size: 20,
                        page_index: 1
                    }
                });
                if (res.statusCode !== 200) {
                    throw new Error('request fail, statusCode: ' + res.statusCode);
                }
                const list = (res.data && res.data.data) ? res.data.data : [];
                this.resultList = list.map((p) => ({
                    title: p.title,
                    address: p.address || '',
                    location: p.location || p._location || { lat: p.latitude, lng: p.longitude },
                    _distance: p._distance
                }));
                if (this.resultList[0] && this.resultList[0].location) {
                    this.latitude = this.resultList[0].location.lat;
                    this.longitude = this.resultList[0].location.lng;
                    this.updateMarker(this.latitude, this.longitude, this.resultList[0].title);
                }
            } catch (err) {
                console.error('关键字搜索失败:', err);
                this.resultList = [];
            } finally {
                this.loading = false;
            }
        },
        // 更新地图标记
        updateMarker(lat, lng, title = '位置') {
            this.markers = [
                {
                    id: 1,
                    latitude: lat,
                    longitude: lng,
                    title,
                    width: 24,
                    height: 24,
                    // 若不存在自定义图标，使用系统默认标记
                    // 小程序端若找不到本地资源会报错，这里留空使用默认
                    // iconPath: '/static/marker.png'
                }
            ];
        },
        // 选择位置回传到上一个页面
        selectLocation(item) {
            try {
                const pages = getCurrentPages();
                const currPage = pages[pages.length - 1];
                const eventChannel = currPage.getOpenerEventChannel && currPage.getOpenerEventChannel();
                if (eventChannel) {
                    eventChannel.emit('locationSelected', {
                        name: item.title,
                        address: item.address,
                        latitude: item.location.lat,
                        longitude: item.location.lng
                    });
                }
            } catch (e) {
                console.error('回传位置失败', e);
            }
            uni.navigateBack();
        },
        // 距离格式化
        formatDistance(d) {
            if (d < 1000) return `${Math.round(d)}m`;
            return `${(d / 1000).toFixed(0)}km`;
        }
    }
};
</script>

<style lang="scss" scoped>
.position-page {
    width: 100%;
    min-height: 100vh;
    background-color: #f5f5f5;
}

.status-bar {
    width: 100%;
    background-color: #ffffff;
}

.custom-nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    background-color: #ffffff;
    border-bottom: 1px solid #f0f0f0;
}

.nav-back {
    position: absolute;
    left: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 44px;
    height: 44px;
    z-index: 1001;
}

.nav-title {
    font-size: 18px;
    font-weight: 700;
    color: #333333;
}

.search-bar {
    padding: 8px 12px;
    margin-top: 44px;
    border-bottom: 1px solid #f0f0f0;
}

.search-input {
    width: 93%;
    height: 36px;
    background: #ffffff;
    border-radius: 18px;
    padding: 0 14px;
    font-size: 14px;
    color: #333333;
}

.map {
    width: 100%;
    height: 320px;
}

.result-list {
    background-color: #ffffff;
    max-height: calc(100vh - 44px - 36px - 420px);
}

.result-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 12px;
    border-bottom: 1px solid #f0f0f0;
}

.item-left {
    min-width: 0;
}

.poi-title {
    font-size: 16px;
    color: #000000;
}

.poi-title.active {
    color: #ff0000;
}

.poi-address {
    margin-top: 4px;
    font-size: 13px;
    color: #999999;
}

.item-right .distance {
    font-size: 14px;
    color: #666666;
}

.no-data {
    text-align: center;
    color: #999999;
    padding: 30px 0;
}
</style>